#include "LoaderMNT.h"
#include <math.h>
#include <fstream>

using namespace std;

namespace glow
{

  MeshData *LoaderMNT::load(const string &filename)
  {
    MeshData * Mp = new MeshData(filename);

    ifstream file(filename.c_str(), ios::in);

    int ncols, nrows, cellsize;
    float xllcorner, yllcorner;
    float NODATA_value;
    string trash;
    float _minZ = 1000000;
    if(filename==""){cout<<"404  file not found"<<endl; return NULL; }
    else{
      if(file){
	file >> trash;
	file >> ncols;
	file >> trash;
	file >> nrows;
	Mp->_nb_vertices=ncols*nrows;
	file >> trash;
	file >> xllcorner;
	file >> trash;
	file >> yllcorner;
	file >> trash;
	file >> cellsize;
	file >> trash;
	file >> NODATA_value;
		
	Mp->_vertices = new float[ncols*nrows*3];
		
	for(int i=0; i<nrows; i++){
	  for (int j=0;j<ncols*3;j+=3){
	    // ncols*i*3+j = coord du point mais dans le tableau 1 Dimension _vertices
	    Mp->_vertices[(ncols*i*3)+j]=(i)*cellsize; 
	    Mp->_vertices[(ncols*i*3)+j+1]=(j/3)*cellsize;
	    file >> Mp->_vertices[(ncols*i*3)+j+2];
			    
	    if(Mp->_vertices[(ncols*i*3)+j+2] < _minZ && 
	       Mp->_vertices[(ncols*i*3)+j+2] != NODATA_value){ 
	      _minZ = Mp->_vertices[(ncols*i*3)+j+2];
	    }
	  }
	}
		
	for (unsigned int a=2; a<Mp->_nb_vertices*3; a+=3){
	  if( Mp->_vertices[a] == NODATA_value ){
	    Mp->_vertices[a]=_minZ;
	  }
	}
		
	/* gen_index(); */
	int ncols=sqrt(Mp->_nb_vertices);
	int nrows=sqrt(Mp->_nb_vertices);

	Mp->_nb_indices= 2*(ncols-1)*(nrows-1);
	Mp->_index = new unsigned int[Mp->_nb_indices*3];


	int k=0;

	for(int i=0; i<(nrows-1); i++)
	  {
	    for (int j=1;j<(ncols);j++)
	      {
		Mp->_index[k]  = (j-1)+i*ncols;
		k++;
		Mp->_index[k]= (j-1)+(i+1)*ncols;
		k++;
		Mp->_index[k]= (j)+i*ncols;
		k++;

		Mp->_index[k]= (j)+i*ncols;
		k++;
		Mp->_index[k]= (j-1)+(i+1)*ncols;
		k++;
		Mp->_index[k]= (j)+(i+1)*ncols;
		k++;
	      } 	
	  } 
	/*
	  gen_texcoords();
	*/
	if(Mp->_nb_vertices!=0)
	  {
	    Mp->_nb_texcoords=Mp->_nb_vertices*2;
	    Mp->_texcoords =new float[Mp->_nb_texcoords];
	    int ncols=sqrt(Mp->_nb_vertices);

	    int k=0;
	    for (int i=0;i<ncols;i++)
	      {
		for (int j=0; j<ncols; j++)
		  {
		    Mp->_texcoords[k]=(float)((float)j/(ncols));
		    k++;
		    Mp->_texcoords[k]=(float)(1.-(float)i/(ncols));
		    k++;
		  }
	      }    
	  }
	else
	  {
	    cout<<"No File Loaded"<<endl;
	    return NULL;
	  }
		
		
      }
      else
	{
	  cout<<"file loading ERROR !!!"<<endl;
	  return NULL;
	}	
		    
    }
    return Mp;
  }

}
